<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="商品状态" clearable style="width: 200px">
          <el-option label="可供购买" :value="'available'" />
          <el-option label="不可供购买" :value="'unavailable'" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增商品</el-button>
      </el-col>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="productList" row-key="id">
      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="name" label="商品名称" width="200"></el-table-column>
      <!-- 商品图片 -->
      <el-table-column label="商品图片" width="120">
        <template #default="scope">
          <img :src="scope.row.image" style="width: 100%; height: 100%" />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="120">
        <template #default="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="类别" width="150"></el-table-column>
      <el-table-column prop="status" label="状态" width="150">
        <template #default="scope">
          <span>{{ scope.row.status == 1 ? '可供购买' : '不可供购买' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="salesVolume" label="销量" width="120"></el-table-column>
      <el-table-column prop="stock" label="库存" width="120"></el-table-column>
      <el-table-column prop="storeId" label="所属店铺" width="120"></el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" type="number" placeholder="请输入商品价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="category">
              <el-input v-model="form.category" placeholder="请输入商品类别" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="选择商品状态">
                <el-option label="可供购买" value=1 />
                <el-option label="不可供购买" value=2 />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣价格" prop="discountPrice">
              <el-input v-model="form.discountPrice" type="number" placeholder="请输入折扣价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销量" prop="salesVolume">
              <el-input v-model="form.salesVolume" type="number" placeholder="请输入销量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input v-model="form.stock" type="number" placeholder="请输入库存数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属商店" prop="storeId">
              <el-select v-model="form.storeId" placeholder="选择所属商店">
                <el-option v-for="item in storesList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input type="textarea" v-model="form.description" placeholder="请输入商品描述" />
            </el-form-item>
          </el-col>
          <!-- 商品图片 -->
          <el-col :span="24">
            <el-form-item label="商品图片" prop="image">
              <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeUpload" @success="handleSuccess" @error="handleError">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
              <div v-if="form.image" class="uploaded-image">
                <img :src="form.image" alt="上传的图片" style="max-width: 100%; margin-top: 10px;" />
              </div>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductList">
import { ref, reactive } from 'vue';
import { listProducts, addProduct, updateProduct, deleteProduct } from "@/api/pages/product";
import { listStores } from "@/api/pages/virtualStore";
import { uploadImage } from "@/utils/upload";

const loading = ref(true);
const open = ref(false);
const showSearch = ref(true);
const title = ref("");
const refreshTable = ref(true);
const storesList = ref([]);
const productList = ref([]);
const form = reactive({
  id: undefined,
  name: "",
  price: 0,
  category: "",
  status: 1,
  discountPrice: null,
  salesVolume: 0,
  stock: 0,
  description: "",
  storeId: undefined,
  image: ""
});
const queryParams = reactive({
  name: "",
  status: undefined
});
const rules = {
  name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  price: [{ required: true, message: "商品价格不能为空", trigger: "blur" }],
  category: [{ required: true, message: "商品类别不能为空", trigger: "blur" }],
};

// 查询商品列表
const getList = () => {
  loading.value = true;
  listProducts(queryParams).then(response => {
    productList.value = response.data;
    loading.value = false;
  });
};

// 获取商店列表
const getStores = () => {
  listStores().then(response => {
    storesList.value = response.data;
    console.log(storesList.value);
  });
}

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 重置表单
const reset = () => {
  Object.assign(form, {
    id: undefined,
    name: "",
    price: 0,
    category: "",
    status: null,
    discountPrice: null,
    salesVolume: 0,
    stock: 0,
    description: ""
  });
};

// 搜索按钮操作
const handleQuery = () => {
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  Object.assign(queryParams, {
    name: "",
    status: undefined
  });
  getList();
};

// 新增按钮操作
const handleAdd = () => {
  reset();
  getStores();
  open.value = true;
  title.value = "新增商品";
};

// 修改按钮操作
const handleUpdate = (row) => {
  Object.assign(form, row);
  open.value = true;
  title.value = "修改商品";
};

// 提交按钮
const submitForm = () => {
  const apiCall = form.id ? updateProduct : addProduct;
  apiCall(form).then(() => {
    getList();
    open.value = false;
  });
};

// 删除按钮操作
const handleDelete = (row) => {
  deleteProduct(row.id).then(() => {
    getList();
  });
};

// 上传成功的回调
const handleSuccess = (response, file) => {
  form.image = response.url; // 更新表单中的图片字段
  console.log('上传成功:', response);
};

// 上传失败的回调
const handleError = (err) => {
  console.error("上传失败:", err);
};

// 上传文件之前的钩子
const beforeUpload = (file) => {
  // 直接返回 true，允许上传
  uploadImage(file).then(data => {
    form.image = data; // 假设服务器返回的 URL 字段是 url
  });
  return true; // 返回 true 表示可以上传
};

// 初始化商品列表
getList();
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: right;
}
</style>